<template>
  <div class="history">
    <div class="header">
      <div class="goback">
        <img :src="goback" alt="" @click.stop="$emit('goback')" />
        <span @click.stop="$emit('goback')">返回</span>
      </div>
      <div class="title">{{ title }}</div>
      <div class="place"></div>
    </div>
    <div
      class="content"
      :style="`min-height: ${loading ? 'calc(100vh - 160px)' : '300px'};`"
      v-loading="loading"
      element-loading-background="#2B2B2B"
      element-loading-spinner="el-icon-loading"
      v-clickOutside="initActiveBlock"
    >
      <el-table
        v-show="!loading"
        :data="tableData"
        style="width: fit-content; max-width: 100%"
        header-cell-class-name="header-row"
        height="calc(100vh - 155px)"
        :cell-class-name="setCellClassName"
        @cell-click="cellClick"
        @cell-dblclick="cellDbClick"
      >
        <el-table-column fixed label="日期" width="40">
          <el-table-column prop="sort" label="排序" width="40" />
        </el-table-column>
        <template v-for="date in dateList">
          <el-table-column :label="date" width="234" :key="date">
            <el-table-column :prop="`name${date}`" width="144" align="left">
              <template #header>
                <div class="name-header">
                  <span
                    >板块名称<span class="num">{{
                      rankOptions[date] ? `第(${rankOptions[date]})` : ''
                    }}</span></span
                  >
                </div>
              </template>
            </el-table-column>
            <el-table-column :prop="`value${date}`" width="90" align="right">
              <template #header>
                <div class="value-header">
                  <span>{{ nameValue[historyIndex] || '' }}</span>
                  <el-tooltip
                    popper-class="tips-tooltip"
                    placement="bottom"
                    effect="dark"
                    :content="config.tipsArr[historyIndex].valueTips"
                  >
                    <img class="icon" :src="tips" alt="" v-defaultCover />
                  </el-tooltip>
                </div>
              </template>
              <template #default="{ row, column }">
                <div>
                  <span> {{ reservedTwo(row[column.property]) }}% </span>
                </div>
              </template>
            </el-table-column>
          </el-table-column>
        </template>
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reqHistory, reqHistoryDetail } from '_a';
import { errorReport, jumpToKlineFenshi, reservedTwo } from '_t';
import type { HistoryRes, RankType } from '@/types/api.ts';
import type { BlockType } from '@/types/api';
import type { HistoryIndex, HistoryTable } from '@/types/history.ts';
import { KLineFenshiId, KLineFenshiPeriod } from '@/types/toolsType';
import { useTimingUpdate } from '@/hooks';
import config from '@/config/index.ts';
const { goback, tips } = config.imgs;
import 'element-ui/lib/theme-chalk/loading.css';

interface Props {
  historyIndex: HistoryIndex;
  title: string;
  blockType: BlockType;
}

const props = withDefaults(defineProps<Props>(), {
  historyIndex: 0,
  title: '',
  blockType: ''
});
interface Emits {
  (e: 'goback'): void;
  (e: 'setSelection', params: { code: string; market: string; name: string; title: string }): void;
}
const emits = defineEmits<Emits>();
const instance = getCurrentInstance() as any;

const nameValue: string[] = ['1日涨幅', 'G占比', '牛占比'];
const rankTypeOptions: RankType[] = ['short', 'medium', 'long'];
// 表格主题内容
const tableData = ref<HistoryTable[]>([]);
// 日期数组
const dateList = ref<string[]>([]);
// 排名数组
const rankOptions = ref<Record<string, number>>({});
// 当前选中的板块代码
const activeBlockCode = ref('');
// 当前选中的板块市场
const activeBlockMarketId = ref('');

// 设置选中的板块边框
const setCellClassName = ({ row, column }: any) => {
  const property = column.property;
  const code = property.replace('name', 'code');
  return (row[code] === activeBlockCode.value ? 'active' : '') + ' body-row';
};

const initActiveBlock = () => {
  activeBlockCode.value = '';
  activeBlockMarketId.value = '';
};

// 点击表格获取code信息
const getBlockInfo = (
  row: any,
  cell: any
): null | { code: string; market: string; name: string } => {
  const date = cell.property.replace('name', '').replace('value', '');
  console.log(row);
  const code = row[`code${date}`];
  const market = row[`market${date}`];
  const name = row[`name${date}`];
  return {
    code,
    market,
    name
  };
};

const cellClick = (row: any, cell: any) => {
  const blockInfo = getBlockInfo(row, cell);
  if (!blockInfo?.code || blockInfo?.code === '--') {
    return;
  }
  const { code, market, name } = blockInfo;
  activeBlockCode.value = code;
  activeBlockMarketId.value = market;
  emits('setSelection', { code, market, name, title: props.title.slice(0, 4) });
  getHistory();
  getHistoryDetail();
};
const cellDbClick = (row: any, cell: any) => {
  const blockInfo = getBlockInfo(row, cell);
  if (!blockInfo?.code || blockInfo?.code === '--') {
    return;
  }
  jumpToKlineFenshi(blockInfo.code, blockInfo.market, KLineFenshiId.kLine, KLineFenshiPeriod.kLine);
};

const loading = ref(true);

// 处理历史数据响应值
const dealHistoryData = (res: HistoryRes['data']) => {
  // 创建临时变量用于存储处理后的数据
  const tempTableData: HistoryTable[] = [];
  // 设置最大长度为20
  const MAXLEN = 20;
  // 循环处理数据
  for (let index = 0; index < MAXLEN; index++) {
    // 设置默认值
    tempTableData[index] = {
      sort: index + 1
    };
    // 处理每个数据项
    res.forEach(item => {
      // 更新临时变量
      tempTableData[index] = {
        ...tempTableData[index],
        // 动态设置键名和键值
        [`name${item.date}`]: item?.list?.[index]?.name || '--',
        [`value${item.date}`]: item?.list?.[index]?.value || '--',
        [`code${item.date}`]: item?.list?.[index]?.code || '--',
        [`market${item.date}`]: item?.list?.[index]?.market || '--'
      };
    });
  }
  // 处理日期列表
  dateList.value = res
    .map(item => item.date)
    .sort((prev, next) => +next.replace(/-/g, '') - +prev.replace(/-/g, ''));
  // 更新表格数据
  tableData.value = tempTableData;
  // 设置加载状态为false
  loading.value = false;
};
/**
 * 获取历史数据的方法。
 * 首先发送请求获取历史数据，然后处理返回的数据以适应表格显示。
 * 如果在获取数据或者处理数据的过程中出现错误，将记录错误并抛出。
 *
 * @returns void
 *
 * @example 使用示例:
 * ```javascript
 * getHistory()
 * ```
 */
const getHistory = () => {
  // 发送请求获取历史数据
  reqHistory({ rank_type: rankTypeOptions[props.historyIndex], block_type: props.blockType })
    .then(dealHistoryData)
    .catch(error => {
      instance.proxy.$messageInfo('获取历史数据失败，请刷新后重试！');
      errorReport({
        name: `获取历史数据列表失败。是第${props.historyIndex}个列表的错误${error.name}`,
        message: error.message,
        stack: error.stack
      });
    });
};

// 获取历史详情的方法
const getHistoryDetail = () => {
  // 发送请求获取历史详情数据
  reqHistoryDetail({
    // 请求参数：代码
    code: activeBlockCode.value,
    // 请求参数：市场
    market: activeBlockMarketId.value,
    // 请求参数：排名类型，从rankTypeOptions数组中获取第props.historyIndex个元素
    rank_type: rankTypeOptions[props.historyIndex]
  })
    .then(res => {
      // 创建一个临时对象来存储处理过的数据
      const tempObj: Record<string, number> = {};
      // 遍历接收到的数据
      res.forEach(item => {
        // 将日期作为键，排名作为值存入临时对象
        tempObj[item.date] = item.rank;
      });
      // 将处理好的数据赋值给rankOptions变量
      rankOptions.value = tempObj;
    })
    .catch(error => {
      errorReport({
        name: `获取历史详情失败。是第${props.historyIndex}个列表的错误${error.name}`,
        message: error.message,
        stack: error.stack
      });
    });
};

// 监听过滤器变化，重新调用接口
watch(
  () => props.blockType,
  () => {
    loading.value = true;
    getHistory();
    rankOptions.value = {};
  }
);

// 定时更新数据
useTimingUpdate(() => {
  getHistory();
  activeBlockCode.value && getHistoryDetail();
});

onMounted(() => {
  getHistory();
});
</script>

<style scoped lang="less">
.history {
  box-sizing: border-box;
  background: #222222;
  border-radius: 4px;
  padding: 14px 8px;
  margin-top: 6px;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .goback {
      display: flex;
      align-items: center;
      flex: 1;
      img {
        width: 16px;
        height: 16px;
        cursor: pointer;
      }
      span {
        padding-left: 4px;
        font-family: MicrosoftYaHei;
        font-size: 14px;
        color: #828282;
        line-height: 18px;
        font-weight: 400;
        cursor: pointer;
      }
    }
    .title {
      flex: 1;
      display: flex;
      justify-content: center;
      font-family: MicrosoftYaHei-Bold;
      font-size: 14px;
      color: #f2f2f2;
      line-height: 18px;
      font-weight: 700;
    }
    .place {
      flex: 1;
    }
  }
  .content {
    width: 100%;
    max-width: 100%;
    margin-top: 8px;
    .name-header {
      .num {
        color: #ffb300;
      }
    }
    .value-header {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      span {
        white-space: nowrap;
      }
      .icon {
        width: 12px;
        height: 12px;
        margin-left: 4px;
        cursor: pointer;
      }
    }
    :deep(.el-table-fixed-column--left) {
      border-right: 1px solid #595959 !important;
      border-left: 1px solid #595959;
    }
    :deep(.el-table.el-table--border:after) {
      width: 0 !important;
    }
    :deep(.el-table.el-table--border:before) {
      width: 0 !important;
    }
    :deep(.el-table--border),
    :deep(.el-table--group) {
      border: 1px solid #595959;
    }
    :deep(.el-table) {
      tr {
        background: #222222;
      }
      background: #222222;
      .el-table__fixed-right::before,
      .el-table__fixed::before {
        display: none;
      }
      .el-table__inner-wrapper::before {
        width: 0 !important;
      }
      &.el-table--border .el-table__inner-wrapper:after,
      &.el-table--border:after,
      &.el-table--border:before,
      .el-table__inner-wrapper:before {
        background-color: #595959;
      }
      .gutter {
        display: none;
      }
      .el-table__border-bottom-patch,
      .el-table__border-left-patch {
        background-color: initial;
      }
      .el-table__inner-wrapper,
      .el-scrollbar__wrap,
      .el-scrollbar__view {
        height: 100%;
      }
      .el-table__cell {
        box-sizing: border-box;
        padding: 8px 0;
      }
      .is-group {
        tr:last-child {
          .header-row {
            &:nth-of-type(even) {
              border-right: 1px solid #323232;
            }
            .cell {
              color: #8c8c8c;
            }
          }
        }
      }
      .header-row {
        background-color: #161616;
      }
      .body-row {
        background-color: #222222;
        cursor: pointer;
        &.active {
          border-left: 1px solid rgba(255, 255, 255, 0.6);
          border-top: 1px solid rgba(255, 255, 255, 0.6);
          border-bottom: 1px solid rgba(255, 255, 255, 0.6);
          & + * {
            border-right: 1px solid rgba(255, 255, 255, 0.6);
            border-top: 1px solid rgba(255, 255, 255, 0.6);
            border-bottom: 1px solid rgba(255, 255, 255, 0.6);
          }
        }
        &:nth-of-type(even) {
          border-right: 1px solid #323232;

          &:hover,
          &:hover + * {
            background-color: #2b2b2b;
          }
        }
      }
      .header-row,
      .body-row {
        border-bottom: 1px solid #323232;
        border-right: 1px solid #595959;
        &:first-child {
          .cell {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 0;
          }
        }
        .cell {
          box-sizing: border-box;
          font-family: MicrosoftYaHeiUI;
          font-size: 14px;
          color: #f2f2f2;
          line-height: 18px;
          font-weight: 400;
          white-space: nowrap;
          padding: 0 12px;
        }
      }
    }
  }
}
</style>
